<?php
$nns_db_dir_db = dirname(dirname ( dirname ( __FILE__ ) ));
$nns_db = dirname ( dirname ( __FILE__ ));
require_once 'nns_db_constant.php';
require_once 'nns_db_error.php';
require_once 'nns_db_common_class.php';
require_once $nns_db_dir_db . DIRECTORY_SEPARATOR . "nn_cms_config.php";
require_once $nns_db.DIRECTORY_SEPARATOR.'nns_debug_log'.DIRECTORY_SEPARATOR.'nns_debug_log_class.php';
include_once $nns_db_dir_db . DIRECTORY_SEPARATOR . 'nn_logic'.DIRECTORY_SEPARATOR.'nl_common.func.php';

class nns_db_class {
	protected $db_type = 1; //用于确定当前操作的数据库，当db_type为1代表mysql，2代表sql server  ，3代表ODBC或其他。
	protected $db_host; //数据库所在主机域名
	protected $db_username; //数据库用户名
	protected $db_password; //数据库密码
	protected $db_name; //数据库名称
	protected $link_id = false; //数据库连接
	protected $connected = false; //数据库连接状态
	protected $query_id = false; //查询结果集
	protected $error_id = array (); //错误信息数组
	public $num_rows = 0; //结果集行数
	public $last_insert_id = null; // 最后插入ID
	private static $DB_TYPE_MYSQL = 1;
	public $log;


	private $config;

	/**
	 *
	 * 设置主机 用户名 及密码函数
	 * @param string $host 主机IP
	 * @param string $username 登陆帐号
	 * @param string $password 密码
	 */
	public function __construct($host, $username, $pwd, $dbname) {
		$this->config=nl_get_db_config(NL_DB_WRITE);

		$this->db_host=$this->config['host'];
		$this->db_username=$this->config['user'];
		$this->db_password=$this->config['passwd'];
		$this->db_name=$this->config['db_name'];


//		$this->db_host = $host;
//		$this->db_username = $username;
//		$this->db_password = $pwd;
//		$this->db_name = $dbname;
        $this->log =  new nns_debug_log_class();
        $this->log->setlogpath('debug_sql');
	}
	//


	/**
	 *
	 *连接数据库函数
	 * @return MySQL 连接标识/false;
	 *
	 */
	public function nns_db_connect($conn = null) {
		//判断函数是否存在，来确定mysql和php 是否安装成功
		switch ($this->db_type) {
			case 1 :
				if ($conn) {
					$this->link_id = $conn;
				} else {
					$this->link_id = new mysqli($this->db_host, $this->db_username, $this->db_password,$this->db_name);
					if (! $this->link_id) {
						$this->error_log('mysql connect failed');
						return $this->nns_db_result ( NNS_ERROR_DB_CONNECT, "mysql connect failed" );
					}
				}
				$this->link_id->query ( "set names utf8 " );
				$this->link_id->query ( "set character_set_client=utf8" );
				$this->link_id->query ( "set character_set_results=utf8" );
				//标记连接成功
				$this->connected = true;
				return $this->link_id;

			case 2 :
			//sql server
			case 3 :

		//odbc
		}
	}

	/**
	 *
	 * 查询语句函数
	 * @param string $sql
	 * @return SELECT，SHOW，EXPLAIN 或 DESCRIBE 语句返回一个资源标识符，如果查询执行不正确则返回 FALSE
	 * 对于其它类型的 SQL 语句(CREATE DATABASE )，在执行成功时返回 TRUE，出错时返回 FALSE
	 */
	public function nns_db_query($sql) {

		if ($this->nns_db_check_sql($sql)===FALSE) return $this->nns_db_result ( NNS_ERROR_DB_SQL_EXEC, "write command refuse" );

		switch ($this->db_type) {
			case 1 :
				$this->link_id->query  ( "set names utf8 " );
				$this->link_id->query  ( "set character_set_client=utf8" );
				$this->link_id->query  ( "set character_set_results=utf8" );

				if ($this->query_id) {
					$this->nns_db_result_free ();
				}
				$this->query_id = $this->link_id->query ($sql);
				if (false === $this->query_id) {

					$this->error_log('nns_db_query failed:'.$sql);
					return $this->nns_db_result ( NNS_ERROR_DB_SQL_EXEC, "mysql execute failed" );
				} else {
					$this->query_id && $this->num_rows = mysqli_num_rows ( $this->query_id );
					return $this->nns_get_all ();
				}

			case 2 :
			//sql server
			case 3 :

		//odbc
		}
	}


	private function nns_db_check_sql($sql){

		if ($this->config['mode']=='READ'){
			if (stripos($sql,'insert')===0 || stripos($sql,'update')===0 || stripos($sql,'delete')===0){
				return FALSE;
			}
		}
		return TRUE;
	}

	/***
	 * 执行语句函数
	 */
	public function nns_db_execute($sql) {

		 if ($this->nns_db_check_sql($sql)===FALSE) return $this->nns_db_result ( NNS_ERROR_DB_SQL_EXEC, "main database down" );

		switch ($this->db_type) {
			case 1 :
				mysqli_query ( $this->link_id,"set names utf8 " );
				mysqli_query ( $this->link_id,"set character_set_client=utf8" );
				mysqli_query ( $this->link_id,"set character_set_results=utf8" );


				if ($this->query_id) {
					$this->nns_db_result_free ();
				}
				$this->query_id = mysqli_query ($this->link_id,$sql );
				if (false === $this->query_id) {

					$this->error_log('mysql execute failed',$sql);
					return $this->nns_db_result ( NNS_ERROR_DB_SQL_EXEC, "mysql execute failed" );
				} else {
					//$this->num_rows = mysql_affected_rows ( $this->query_id );
					//$this->last_insert_id = mysql_insert_id ( $this->query_id );
					//$result = array ();
					//$result = $this->num_rows;
					return $this->nns_db_result ( NNS_ERROR_OK, "mysql execute ok" );
				}

			case 2 :
			//sql server
			case 3 :
		}
		return $this->nns_db_result ( NNS_ERROR_DB_SQL_EXEC, "is no mysql query" );
	}

	private function nns_get_all() {
		$result = array ();
		if ($this->num_rows > 0) {
			while ( $row = mysqli_fetch_assoc ( $this->query_id ) ) {
				$result [] = $row;
			}
			mysqli_data_seek ( $this->query_id, 0 );
		}
		return $this->nns_db_result ( NNS_ERROR_OK, "mysql query ok", $result );
	}

	/***
	 * 错误返回 或结果集返回...
	 * @param string $ret
	 * @param string $reason
	 * @param array $data
	 * @return
	 */
	public function nns_db_result($ret, $reason, $data = array()) {
		$this->error_id ["ret"] = $ret;
		$this->error_id ["reason"] = $reason;
		$this->error_id ["data"] = $data;
		return $this->error_id;

	}
	/**
	 *
	 * 释放结果集内存
	 * @param string $dataResult
	 * @return true /false
	 */
	public function nns_db_result_free() {
		switch ($this->db_type) {
			case 1 :
				if (is_resource($this->query_id )){
					mysqli_free_result ( $this->query_id );
				}
					$this->query_id = false;

			case 2 :
			//sql server
			case 3 :

		// odbc
		}
	}

	/**
	 *
	 * 释放数据库链接资源
	 * @param string $dataResult
	 * @return true /false
	 */
	public function nns_db_link_free() {
		switch ($this->db_type) {
			case 1 :
				if ($this->link_id != false) {
					mysqli_close ( $this->link_id );
					$this->link_id = false;
				}

			case 2 :
			//sql server
			case 3 :

		// odbc
		}
	}
    public function insert_id()
    {
        return mysqli_insert_id($this->link_id);
	}

	//added by xyl 2012-10-11 15:32:54
	public function last_id(){
		return mysqli_insert_id($this->link_id);
	}
	/**
	 *
	 * 关闭数据库
	 * @param string $conn
	 * @return true /false
	 */
	public function nns_db_close() {
		switch ($this->db_type) {
			case 1 :
				$this->nns_db_result_free ();
				$this->nns_db_link_free ();
			case 2 :
			//sql server
			case 3 :

		//odbc
		}
	}
	/**
	 *
	 * 关闭数据库连接
	 */
	public function __destruct() {
		$this->nns_db_close ();
	}
	function error_log($message = '', $sql = '') {
		$dberror = $this->error();
		$dberrno = $this->errno();
        $this->log->write($message."\n".$dberrno." ".$dberror."\n".$sql);

		/*echo "<div style=\"position:absolute;font-size:11px;font-family:verdana,arial;background:#EBEBEB;padding:0.5em;\">
				<b>MySQL Error</b><br>
				<b>Message</b>: $message<br>
				<b>SQL</b>: $sql<br>
				<b>Error</b>: $dberror<br>
				<b>Errno.</b>: $dberrno<br>
				</div>";
		exit();*/
	}
	function error() {
		return (($this->link_id) ? mysqli_error($this->link_id) : mysqli_error($this->link_id));
	}

	function errno() {
		return intval(($this->link_id) ? mysqli_errno($this->link_id) : mysqli_errno($this->link_id));
	}
}
?>